package h0904;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 不知名帅哥
 * @version 1.0
 * @description 前k个高频单词
 * @date 2024/9/4 11:56
 */
public class FirstKFrequencyWords {
    public static void main(String[] args) {
        String[] words = {"i", "love", "leetcode", "i", "love", "coding"};
        int k = 2;
        System.out.println(topKFrequent2(words, k));
    }

    public static List<String> topKFrequent(String[] words, int k) {
        HashMap<String, Integer> map = new HashMap<>();
        for (int i = 0; i < words.length; i++) {
            map.put(words[i], map.getOrDefault(words[i], 0) + 1);
        }
        List<String> list = map.keySet().stream().sorted((a, b) -> {
            int m = map.get(a);
            int n = map.get(b);
            if (m != n) {
                return n - m;
            } else {
                return a.compareTo(b);
            }
        }).toList();

        return list.subList(0, k);
    }

    public static List<String> topKFrequent2(String[] words, int k) {
        HashMap<String, Integer> map = new HashMap<>();
        for (int i = 0; i < words.length; i++) {
            map.put(words[i], map.getOrDefault(words[i], 0) + 1);
        }
        PriorityQueue<String> queue = new PriorityQueue<>((a, b) -> {
            int m = map.get(a);
            int n = map.get(b);
            if (m != n) {
                return m-n;
            } else {
                return b.compareTo(a);
            }
        });
        for (String s : map.keySet()) {
            queue.offer(s);
            if (queue.size() > k) {
                //将较小的单词弹出去
                queue.poll();
            }
        }
        List<String> ans = new ArrayList<>();
        while (!queue.isEmpty()) {
            ans.add(queue.poll());
        }
        Collections.reverse(ans);
        return ans;
    }
}
